package com.xwj.coupon.user.mq.producer;

import com.xwj.coupon.user.common.constant.UserCouponRocketMQConstant;
import com.xwj.coupon.user.mq.message.CouponTemplateMessageBody;
import com.xwj.coupon.user.mq.message.CreateUserCouponMessageBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Author: XuWenjie
 * @Date: 2025-08-19
 * @Description: AssignUserCouponMqProducer
 */
@Slf4j
@Component
public class AssignUserCouponMqProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //优惠券创建消息
    public boolean sendMessage(CreateUserCouponMessageBody messageBody, String key) {

        // 2. 构建消息
        String destination = UserCouponRocketMQConstant.USER_COUPON_MQ_TOPIC + ":" + UserCouponRocketMQConstant.USER_COUPON_CREATE_TAG;

        Message<CreateUserCouponMessageBody> message = MessageBuilder.withPayload(messageBody)
                .setHeader(MessageConst.PROPERTY_KEYS, key) // 设置KEYS方便查询
                .build();

        // 3. 发送
        SendResult sendResult = rocketMQTemplate.syncSend(destination, message);
        log.info("sendMessage topic:{}-key[]-data[{}]-结果:{}", UserCouponRocketMQConstant.USER_COUPON_MQ_TOPIC, message, sendResult.toString());
        return SendStatus.SEND_OK.equals(sendResult.getSendStatus());
    }
}
